const axios = require("axios");
const fs = require("fs");
const apiUrl = "https://iot-api.heclouds.com/thingmodel/query-device-property";
const apiUrl1 =
  "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=60dc4e97-0f75-4fc3-8aba-420a0e8b4112";
const apiUrl2 = "https://iot-api.heclouds.com/thingmodel/set-device-property";
const deviceName = "d1";
const productid = "zy1NTZomN9";
const authorizationKey =
  "version=2022-05-01&res=userid%2F378829&et=1745595703&method=sha1&sign=MbkKStlGzWOmL1%2BbgO3bkDcCYYQ%3D"; // 请将 'your_authorization_key' 替换为实际的授权 key

const headers = {
  authorization: authorizationKey,
};

let posttime;

let postst;

// 读取文件的路径
const filePath = "D:/develop/python/pythonProject4/address.txt";

// 使用fs.readFile异步方法读取文件内容
fs.readFile(filePath, "utf8", (err, data) => {
  if (err) {
    console.error("读取文件时出错:", err);
    return;
  }

  // 打印文件内容
  console.log("文件内容:", data);
});

function monitorAndSendRequest() {
  
  setInterval(async () => {
    try {
      axios
        .get(
          apiUrl,
          {
            params: {
              device_name: "d1",
              product_id: "zy1NTZomN9",
            },
            headers: headers,
          },
          { timeout: 10000 }
        )
        .then((response) => {
          // console.log(response.data); // 输出返回的数据内容
          const data = response.data.data;

          const testValue = data.find(
            (item) => item.identifier === "test"
          ).value;
          const humiValue = data.find(
            (item) => item.identifier === "humi"
          ).value;
          const tempmaxValue = data.find(
            (item) => item.identifier === "tempmax"
          ).value;
          const humimaxValue = data.find(
            (item) => item.identifier === "humimax"
          ).value;
          const LEDvalue = data.find((item) => item.identifier === "led").value;
          const BEEValue = data.find((item) => item.identifier === "bee").value;
          const posttime = data.find((item) => item.identifier === "humi").time;
                   console.log(posttime)
          // 定义一个毫秒级时间戳
          const postTimeMillis = posttime;
          // 创建一个新的 Date 对象，直接传入毫秒级时间戳
          const date = new Date(postTimeMillis);

          // 使用 Date 对象的方法获取年、月、日、时、分、秒等信息
          const year = date.getFullYear();
          const month = date.getMonth() + 1; // 月份从 0 开始，所以要加 1
          const day = date.getDate();
          const hours = date.getHours();
          const minutes = date.getMinutes();
          const seconds = date.getSeconds();

          // 将获取到的信息组合成想要的时间格式
          //         const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
          const formattedTime = `${hours}:${minutes}:${seconds}`;
          //          console.log(LEDvalue,BEEValue)
          //         console.log(formattedTime);

          let currentTime = Date.now();
          // console.log(currentTime);
          let timeDifference = currentTime - postTimeMillis;

         // console.log(timeDifference);
          //console.log(postst);
          postst = false;
          if (timeDifference < 10000 && !postst) {
            postst = true
            //           console.log("时间差小于 10 秒");
          } else {
            //            this.onst = false;
            postst = false;
            console.log("时间差大于等于 10 秒");
            axios
              .post(apiUrl1, {
                msgtype: "news",
                news: {
                  articles: [
                    {
                      title: `警告,设备已掉线${formattedTime}`,
                      description: `时间:${formattedTime}`,
                      url: "https://static-mp-6e448d05-1c65-466c-955e-3663779b9553.next.bspapp.com",
                      picurl:
                        "https://mp-6e448d05-1c65-466c-955e-3663779b9553.cdn.bspapp.com/cloudstorage/高达系列④壁纸5.png",
                    },
                  ],
                },
              })
              .then((response) => {
                console.log("POST 请求成功:", response.data);
              })
              .catch((error) => {
                console.error("POST 请求失败:", error);
              });
          }

          if (LEDvalue == "true") {
            console.log("LED");
            axios
              .post(apiUrl1, {
                msgtype: "news",
                news: {
                  articles: [
                    {
                      title: `${formattedTime}提示,LED已打开`,
                      description: `时间:${formattedTime}`,
                      url: "https://static-mp-6e448d05-1c65-466c-955e-3663779b9553.next.bspapp.com",
                      picurl:
                        "https://mp-6e448d05-1c65-466c-955e-3663779b9553.cdn.bspapp.com/cloudstorage/高达系列④壁纸5.png",
                    },
                  ],
                },
              })
              .then((response) => {
                console.log("POST 请求成功:", response.data);
              })
              .catch((error) => {
                console.error("POST 请求失败:", error);
              });
          }

          if (BEEValue == "true") {
            console.log("BEE");
            axios
              .post(apiUrl1, {
                msgtype: "news",
                news: {
                  articles: [
                    {
                      title: `${formattedTime}提示,报警器已打开`,
                      description: `时间:${formattedTime}`,
                      url: "https://static-mp-6e448d05-1c65-466c-955e-3663779b9553.next.bspapp.com",
                      picurl:
                        "https://mp-6e448d05-1c65-466c-955e-3663779b9553.cdn.bspapp.com/cloudstorage/高达系列④壁纸5.png",
                    },
                  ],
                },
              })
              .then((response) => {
                console.log("POST 请求成功:", response.data);
              })
              .catch((error) => {
                console.error("POST 请求失败:", error);
              });
          }

          if (
            parseFloat(testValue) >= tempmaxValue ||
            parseFloat(humiValue) >= humimaxValue
          ) {
            //           console.log("报警");
            let warntext = axios
              .post(apiUrl1, {
                msgtype: "news",
                news: {
                  articles: [
                    {
                      title: `警告,温度:${testValue},湿度:${humiValue}`,
                      description: `时间:${formattedTime}`,
                      url: "https://static-mp-6e448d05-1c65-466c-955e-3663779b9553.next.bspapp.com",
                      picurl:
                        "https://mp-6e448d05-1c65-466c-955e-3663779b9553.cdn.bspapp.com/cloudstorage/高达系列④壁纸5.png",
                    },
                  ],
                },
              })
              .then((response) => {
                console.log("POST 请求成功:", response.data);
              })
              .catch((error) => {
                console.error("POST 请求失败:", error);
              });
          } else {
            //           console.log("未达到报警","rep:", humimaxValue,"humi:",tempmaxValue);
          }
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    } catch (error) {
      console.error("Error:", error);
    }
  }, 5000); // 每隔5秒执行一次
}

monitorAndSendRequest();
